﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using T.S.BaseData.Api.AppClinet.Commend.Users;
using T.S.BaseData.Api.Dto.User;
using T.S.BaseData.Domain.Entity;
using T.S.BaseData.ErrorCode;
using T.S.BaseData.Infrastructure.Base;


namespace T.S.BaseData.Api.AppClinet.CommendHand.Users
{
    public class UserLoginCommandHandle : IRequestHandler<UserLoginCommand, ApiResult<LoginUserDto>>
    {
        private readonly IBaseRepository<User> usreRepo;
        private readonly IMapper mapper;
        private readonly ILogger<UserLoginCommandHandle> logger;
        private readonly IConfiguration config;

        public UserLoginCommandHandle(IBaseRepository<User> usreRepo,
            IMapper mapper,
            ILogger<UserLoginCommandHandle> logger,
            IConfiguration config)
        {
            this.usreRepo = usreRepo;
            this.mapper = mapper;
            this.logger = logger;
            this.config = config;
        }

        public Task<ApiResult<LoginUserDto>> Handle(UserLoginCommand request, CancellationToken cancellationToken)
        {

            var user = usreRepo.GetAll();

            ApiResult<LoginUserDto> result = new ApiResult<LoginUserDto>();

            var model = user.Where(x => x.UserName == request.UserName).AsNoTracking().FirstOrDefault();
            if (model==null)
            {
                result.Code = ApiEnums.Error;
                result.Data = null;
                result.Meg = "用户名错误,请重新登录";

                return Task.FromResult(result);
            }

            if (model.UserPass == request.UserPass)
            {
                LoginUserDto Dto = new LoginUserDto()
                {
                    UserName = request.UserName,
                    UserReal = model.UserReal,
                    Token = CreateTokenString()
                };

                result.Code = ApiEnums.Success;
                result.Data = Dto;
                result.Meg = "登录成功"; 

            }
            else
            {
                result.Code = ApiEnums.Error;
                result.Data = null;
                result.Meg = "密码错误,请重新登录";
            }

            return Task.FromResult(result);
        }



        private string CreateTokenString()
        {
            //var claims = new Claim[] ;
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(config["Jwt:Sercer"]);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }


    }
}
